import { Grid } from '@r-magician/ui';
import { Button, Input, Modal, Space, Tooltip } from 'antd';
import React, { memo, useCallback, useMemo, useState } from 'react';
import './style.less';
import Icon from '../Icon';
import { useFloatLayer } from '@r-magician/hooks';
import { cssClass } from '../../utils/common';
import classNames from 'classnames';
import variables from '../../lib/themeVariables';

const iconCls = cssClass('icon-selector');

const IconSelector = ({ value, onChange }) => {
  const [state, setState] = useState(() => value || '');
  const update = useCallback(
    () => onChange && onChange(state),
    [state, onChange],
  );

  const { visible, okHandle, open, close } = useFloatLayer({
    onConfirm() {
      update();
      return Promise.resolve(true);
    },
  });
  const [searchValue, setSearchValue] = useState('');
  const searchList = useMemo(() => {
    return Icon.iconNames.filter((item) => {
      return !searchValue ? true : item.includes(searchValue);
    });
  }, [searchValue]);
  return (
    <div className={iconCls()}>
      <div className={iconCls('selected')}>
        <div className={iconCls('selected-icon')}>
          {state ? (
            <Tooltip title={state}>
              <Icon type={state} />
            </Tooltip>
          ) : (
            <span className={iconCls('selected-icon-placeholder')}>未选择</span>
          )}
        </div>
        <Button type="link" onClick={open}>
          点击选择icon
        </Button>
      </div>
      <Modal
        visible={visible}
        title="选择图标"
        onOk={okHandle}
        destroyOnClose
        onCancel={close}
      >
        <Space direction="vertical" style={{ width: '100%' }}>
          <Input
            value={searchValue}
            onChange={(e) => setSearchValue(e.target.value)}
          />
          <Grid
            col={6}
            style={{
              height: 500,
              overflow: 'hidden scroll',
              padding: variables.space,
            }}
          >
            {searchList.map((name) => {
              return (
                <Tooltip key={name} title={name}>
                  <div
                    className={classNames(
                      iconCls('icon-wrapper'),
                      state === name && 'active',
                    )}
                    onClick={() => setState(name)}
                  >
                    <Icon type={name} />
                  </div>
                </Tooltip>
              );
            })}
          </Grid>
        </Space>
      </Modal>
    </div>
  );
};

export default memo(IconSelector);
